<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    table {
      width: 100%;
      border-collapse: collapse;
    }
  </style>
</head>

<body>
  <table border>
    <thead id="table-thead"></thead>
    <tbody id="table-body"></tbody>
  </table>
  <script src="./header.js"></script>
  <script src="./data.js"></script>
  <script src="./header-core.js"></script>
  <script src="./body.core.js"></script>
  <script>
    const { columns, tableColumnTree, metricColumn, tableHeader } = HeaderCore.create(headerConfig, data)
    console.log('生成的TableHeader：', tableHeader)
    console.log(columns)
    const { dataList, renderColumns, cellMerge } = BodyCore.create(columns, data);

    // 渲染表格
    function renderTableHeader(data) {
      const trStr = data.map(tr => {
        const tdStr = tr.map(td =>  `<th colspan="${td.colspan}" rowspan="${td.rowspan}">${td.title}</td>`).join('');
          return `<tr>${tdStr}</tr>`;
      }).join('')
      document.getElementById('table-thead').innerHTML = trStr;
    }

    console.log('cellMerge', cellMerge)

    // 渲染表体
    function renderTableBody(data) {
      console.log('data', data)
      console.log('renderColumns', renderColumns)

      const trStr = data.map((tr, rowIdx) => {
        let tds = renderColumns.map(td => {
          const { dataIndex } = td;
          const mergeInfo = cellMerge[dataIndex][rowIdx]
          // 存在合并，并且是合并的第一个；
          if (mergeInfo.rowspan > 1 && mergeInfo.rowspanIndex === 0) {
            return `<td data-index="${td.dataIndex}-${rowIdx}" rowspan="${mergeInfo.rowspan}">${typeof tr[td.dataIndex] === 'undefined' ? '' : tr[td.dataIndex]}</td>`
          }
          // 存在合并，但是不是合并的头部第一个，所以需要删除
          if (mergeInfo.rowspan === 1) {
            return `<td data-index="${td.dataIndex}-${rowIdx}">${typeof tr[td.dataIndex] === 'undefined' ? '' : tr[td.dataIndex]}</td>`;
          }
          return ''
        })
        let rowStr = `<tr>\n${tds.join('\n')}\n</tr>`;
        return rowStr
      }).join('\n')
      document.getElementById('table-body').innerHTML = trStr
    }

    renderTableHeader(tableHeader)
    renderTableBody(dataList)
  </script>
</body>

</html>